package com.yinhai.message.implement.sms.util;

import java.io.Reader;
import java.io.StringReader;
import java.util.Iterator;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

import com.yinhai.core.common.api.config.impl.SysConfig;
import com.yinhai.message.core.util.HttpPoolManager;

/**
 * 成都社保局
 * @author yanglq
 * 2017.6.19
 */
public class SmsHttpsSendUtil {
	
	private static SmsHttpsSendUtil smsHttps = null;
	
 //    String testUrl="https://od.cdhrss.gov.cn:8045/yhjypt/services/yinHaiBusiness?wsdl";//外网正式地址
	private static String testUrl = null;//内网正式地址
    
	public static SmsHttpsSendUtil getInstance(){
		if(smsHttps == null){
			synchronized(SmsHttpsSendUtil.class){
				if(smsHttps == null){
					testUrl = SysConfig.getSysConfig("smsUrl");
					smsHttps = new SmsHttpsSendUtil();
				}
			}
		}
		return smsHttps;
	}
	
	/**
     * 以httppost的方式调用平台的callBusiness方法 
     * @return
	 * @throws Exception 
     */
	public String httpPostCallBusiness(String inputXml,String username,String password,String funNo) throws Exception {
		CloseableHttpClient httpclient = HttpPoolManager.getHttpClient();
		String returnxml = "";
        try {
	   	    HttpPost httppost = new HttpPost(testUrl);//内网地址 
	   	    httppost.setHeader("Content-Type", "application/soap+xml; charset=utf-8");
	   	    String callbusinessXml = getCallBusinessReqXml(username,password,inputXml,funNo);
	   		// 设置请求的数据
	   		StringEntity httppostEntity = new StringEntity(callbusinessXml,"UTF-8");
	   		httppostEntity.setContentType("text/xml; charset=utf-8");
	   		httppost.setEntity(httppostEntity);
	   		// 执行
	   		CloseableHttpResponse response = httpclient.execute(httppost);
	   		HttpEntity entity = response.getEntity();
	   		//返回结果处理
	   		try {  
                if (entity != null) { 
                	returnxml = getReturnXml(EntityUtils.toString(entity, "UTF-8"));
                }else {
                	returnxml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><result><code>-1</code><message>没有获取到平台返回的内容!</message></result>";
				}  
            } finally {  
                response.close();  
            }  
        } catch (Exception e) {
        	returnxml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><result><code>-1</code><message>"+e.getMessage()+"</message></result>";
        } finally {  
            // 关闭连接,释放资源    
//            try {  
//                httpclient.close();  
//            } catch (IOException e) {  
//                e.printStackTrace(); 
//                returnxml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><result><code>-1</code><message>"+e.getMessage()+"</message></result>";
//            }  
        }
		return returnxml;
	}
	
	public String getReturnXml(String soapXML) throws Exception {
		String returnxml = "";
		SAXBuilder sb = new SAXBuilder();
        Reader rd = new StringReader(soapXML);
        org.jdom.Document docArg = sb.build(rd);
        Element rootArg = docArg.getRootElement();
        List lstArg = rootArg.getChildren();
        for (Iterator iter = lstArg.iterator(); iter.hasNext(); ) {
          Element el = (Element)iter.next();
          try
          {
        	if (el.getName().equalsIgnoreCase("Body")){
        		returnxml = el.getValue().toString();
        	}
          }
          catch (Exception e)
          {
        	  returnxml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><result><code>-1</code><message>没有获取到返回内容 :"+e.getMessage()+"</message></result>";
          }
        }
	       return returnxml;
	   }

    /**
     * 根据输入参数拼装调用callBusiness的soap的xml串 
     * @return
     */
    private String getCallBusinessReqXml(String username,String password,String inputxml,String jybh)
    {
        inputxml = inputxml.replaceAll("<", "&lt;");
        inputxml = inputxml.replaceAll(">", "&gt;");
        inputxml = inputxml.replaceAll("\"", "&quot;");
        StringBuilder soapRequestData = new StringBuilder();
        soapRequestData.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
        			   .append("<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">")
        			   .append("  <soap:Header>")
        			   .append("   <in:system xmlns:in=\"http://yinhai.com\">")
        			   .append("    <userName>"+username+"</userName>")
        			   .append("    <passWord>"+password+"</passWord>")
        			   .append("    <jylsh>0</jylsh>")
        			   .append("    <jyyzm>0</jyyzm>")
        			   .append("    <jybh>"+jybh+"</jybh>")
        			   .append("   </in:system>")
        			   .append("  </soap:Header>")
        			   .append("  <soap:Body>")
        			   .append("   <ns2:callBusiness xmlns:ns2=\"http://webservice.common.yinhai.com/\">")
        			   .append("   <inputxml>" + inputxml + "</inputxml>")
        			   .append("   </ns2:callBusiness>")
        			   .append("  </soap:Body>")
        			   .append("</soap:Envelope>");
        return soapRequestData.toString();
    }
}
